<template>
  <div class="management-page">
    <!-- 页面标题 -->
    <div class="page-title">
      <h2>加达币明细管理</h2>
    </div>
    
    <!-- 搜索和操作区 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入用户昵称/订单号搜索"
        clearable
        style="width: 300px;"
        @keyup.enter="loadData"
      >
        <template #append>
          <el-button type="primary" @click="loadData">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </template>
      </el-input>
      
      <el-button type="warning" @click="exportData">
        <el-icon><Download /></el-icon>
        导出数据
      </el-button>
    </div>
    
    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      size="small"
      v-loading="loading"
      style="width: 100%; margin-top: 15px;"
    >
      <el-table-column 
        prop="index" 
        label="序号" 
        width="80" 
        align="center"
        fixed
      ></el-table-column>
      <el-table-column 
        prop="userNickname" 
        label="用户昵称" 
        min-width="120"
      ></el-table-column>
      <el-table-column 
        prop="加达币" 
        label="加达币" 
        min-width="100"
        align="right"
      >
        <template #default="scope">
          <span :class="scope.row.changeType === '减少' ? 'text-danger' : 'text-success'">
            {{ scope.row.changeType === '减少' ? '-' : '+' }}{{ scope.row.加达币 }}
          </span>
        </template>
      </el-table-column>
      <el-table-column 
        prop="changeType" 
        label="增减类型" 
        min-width="100"
      >
        <template #default="scope">
          <el-tag :type="scope.row.changeType === '增加' ? 'success' : 'danger'">
            {{ scope.row.changeType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column 
        prop="detailType" 
        label="明细类型" 
        min-width="120"
      ></el-table-column>
      <el-table-column 
        prop="orderNo" 
        label="订单号" 
        min-width="180"
      ></el-table-column>
      <el-table-column 
        prop="time" 
        label="时间" 
        min-width="160"
      ></el-table-column>
      <el-table-column 
        prop="year" 
        label="时间年" 
        min-width="100"
      ></el-table-column>
      <el-table-column 
        prop="month" 
        label="时间月" 
        min-width="120"
      ></el-table-column>
      <el-table-column 
        prop="day" 
        label="时间日" 
        min-width="120"
        fixed="right"
      ></el-table-column>
    </el-table>
    
    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 15px;"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, Download } from '@element-plus/icons-vue';

// 状态管理
const tableData = ref([]);
const loading = ref(false);
const searchQuery = ref('');

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 页面加载时获取数据
onMounted(() => {
  loadData();
});

// 生成模拟数据
const generateMockData = (page, pageSize) => {
  const data = [];
  const totalItems = 87; // 总数据条数
  const startIndex = (page - 1) * pageSize + 1;
  const endIndex = Math.min(startIndex + pageSize - 1, totalItems);
  
  // 明细类型列表
  const detailTypes = [
    '分销返现', '消费抵扣', '签到奖励', '邀请奖励', 
    '系统赠送', '任务完成', '兑换商品', '退款返还'
  ];
  
  for (let i = startIndex; i <= endIndex; i++) {
    const isIncrease = Math.random() > 0.4; // 60%概率为增加，40%为减少
    const amount = Math.floor(Math.random() * 100) + 1;
    const date = new Date();
    date.setDate(date.getDate() - Math.floor(Math.random() * 30));
    
    data.push({
      index: i,
      userNickname: `用户${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`,
      加达币: amount,
      changeType: isIncrease ? '增加' : '减少',
      detailType: detailTypes[Math.floor(Math.random() * detailTypes.length)],
      orderNo: `ORD${Date.now().toString().slice(-8)}${i.toString().padStart(4, '0')}`,
      time: date.toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(',', ''),
      year: date.getFullYear().toString(),
      month: `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}`,
      day: `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    });
  }
  
  return { data, total: totalItems };
};

// 加载数据
const loadData = () => {
  loading.value = true;
  
  // 模拟API请求延迟
  setTimeout(() => {
    try {
      const { data, total } = generateMockData(pagination.value.currentPage, pagination.value.pageSize);
      
      // 处理搜索逻辑
      let filteredData = [...data];
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase();
        filteredData = data.filter(item => 
          item.userNickname.toLowerCase().includes(query) || 
          item.orderNo.toLowerCase().includes(query)
        );
      }
      
      tableData.value = filteredData;
      pagination.value.total = filteredData.length ? total : 0;
    } catch (error) {
      ElMessage.error('数据加载失败，请重试');
      console.error('加载失败:', error);
    } finally {
      loading.value = false;
    }
  }, 600);
};

// 导出数据
const exportData = () => {
  loading.value = true;
  
  // 模拟导出操作
  setTimeout(() => {
    try {
      ElMessage.success('数据导出成功');
    } catch (error) {
      ElMessage.error('导出失败，请重试');
    } finally {
      loading.value = false;
    }
  }, 1000);
};

// 分页事件处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  loadData();
};

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page;
  loadData();
};
</script>

<style scoped>
.management-page {
  padding: 20px;
  background-color: #ffffff;
  min-height: calc(100vh - 40px);
}

.page-title {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e7eb;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.pagination-container {
  text-align: right;
}

.text-success {
  color: #10b981;
}

.text-danger {
  color: #ef4444;
}
</style>
